<?php
namespace app\admin\controller;

use app\common\lib\IAuth;
use think\Controller;

class Login extends Base
{
    public function _initialize(){}
    public function index()
    {
        $isLogin = $this->isLogin();
        if($isLogin){
            return $this->redirect('index/index');
        }else{
            //如果后台用户已经登录
            return $this->fetch();
        }
    }
    public function check(){
        if(request()->isPost() ){
            $data = input('post.');
            if(!captcha_check($data['code'])){
                $this->error('验证码不正确');
            }
            $validate = validate('AdminUser');
            if(!$validate->check($data)){
                $this->error($validate->getError());
            }
            try{
                //判断用户名是否存在
                $username = model('AdminUser')->get(['username'=>$data['username']]);
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            if (!$username || $username->status != config('code.status_normal')){
                $this->error('用户名不存在');
            }
            if(IAuth::setPassword($data['password']) != $username['password']){
                $this->error('密码不正确');
            }
            //更新数据库 登陆IP 登陆时间
            $udata = [
              'last_login_time' => time(),
              'last_login_ip' => request()->ip(),
            ];
            try {
                model('AdminUser')->save($udata, ['id' => $username->id]);
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            //2.存入session
            session(config('admin.session_user'),$username ,config('admin.session_user_scope'));
            $this->success('登陆成功','Index/index');
        }else{
            $this->error('验证码不合法');
        }

    }

    /**
     * 退出登录
     */
    public function logout(){
        session(null,config('admin.session_user_scope'));
        $this->redirect('login/index');
    }
}
